package com.hz.friends.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.callback.BitmapAjaxCallback;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.hz.friends.application.CustomApplication;
import com.hz.friends.chat.Helper.CCPIntentUtils;
import com.hz.friends.chat.entity.IMChatMessage;
import com.hz.friends.db.DBContactUser;
import com.hz.friends.serverrequest.ALCCPEngine;
import com.hz.friends.serverrequest.ALUserEngine;
import com.hz.friends.serverrequest.ALEngineConfig.CallBack;
import com.hz.friends.utils.BitmapUtils;
import com.hz.friends.utils.DensityUtil;
import com.hz.friends.utils.MLog;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class InviteFriendsActivity extends BaseActivity {
	private PullToRefreshListView mlistview;
	private LinearLayout layout_select;
	private int limit = 100;
	private MyAdpter adpter;
	private AQuery aq;
	private Button btn_invite;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_invitefriends);
		init();
		initViews();
	}

	@Override
	protected void init() {
		aq = new AQuery(this);
	}

	@Override
	protected void initViews() {
		ImageButton imbtn_bar_left = (ImageButton) findViewById(R.id.imbtn_bar_left);
		ImageButton imbtn_bar_right = (ImageButton) findViewById(R.id.imbtn_bar_right);
		TextView imbtn_bar_title = (TextView) findViewById(R.id.imbtn_bar_title);
		imbtn_bar_right.setVisibility(View.INVISIBLE);
		imbtn_bar_left.setImageResource(R.drawable.ic_leftback_arrow);
		imbtn_bar_title.setText("Invitation");
		imbtn_bar_left.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		layout_select = (LinearLayout) findViewById(R.id.layout_select);
		btn_invite = (Button) findViewById(R.id.btn_invite); // 邀请
		mlistview = (PullToRefreshListView) findViewById(R.id.mlistview);
		adpter = new MyAdpter(this);
		mlistview.setAdapter(adpter);

		uploadFolloweeList();

	}

	private void addImage(AVUser avuser) {
		// 检测是否已有
		for (int i = 0; i < layout_select.getChildCount(); i++) {
			View itemView = layout_select.getChildAt(i);
			if (avuser.getObjectId().equals(itemView.getTag())) {
				return;
			}
		}

		final int width = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 45, getResources()
						.getDisplayMetrics());
		int rigthmarigh = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 5, getResources()
						.getDisplayMetrics());
		LinearLayout.LayoutParams lap = new LinearLayout.LayoutParams(width,
				width);
		lap.rightMargin = rigthmarigh;

		final ImageView imv = new ImageView(this);
		imv.setLayoutParams(lap);
		imv.setTag(avuser.getObjectId());
		// default image
		Bitmap crclebitmap = BitmapUtils.drawCycleImage("#c4c4c5", width);
		Bitmap crclestrokebitmap = BitmapUtils.getCircleStrokbitmap(this,
				crclebitmap, width, 1, "#eeeeee");
		imv.setBackgroundDrawable(new BitmapDrawable(crclestrokebitmap));

		aq.id(imv).image(avuser.getString("headViewURL"), true, true, width, 0,
				new BitmapAjaxCallback() {
					@Override
					protected void callback(String url, ImageView iv,
							Bitmap bm, AjaxStatus status) {
						super.callback(url, iv, bm, status);
						Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(
								InviteFriendsActivity.this, bm, width, 1,
								"#eeeeee");
						imv.setImageBitmap(mbitmap);
						imv.setBackgroundColor(Color.TRANSPARENT);
					}
				});

		layout_select.addView(imv);
		btn_invite.setEnabled(true);
	}

	private void deleteImage(AVUser avuser) {
		// 检测是否已有
		for (int i = 0; i < layout_select.getChildCount(); i++) {
			View itemView = layout_select.getChildAt(i);
			if (avuser.getObjectId().equals(itemView.getTag())) {
				layout_select.removeViewAt(i);
				break;
			}
		}
		if (layout_select.getChildCount() == 0)
			btn_invite.setEnabled(false);
		else
			btn_invite.setEnabled(true);

	}

	@Override
	protected void setViews() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void initEvents() {
		mlistview.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
			}

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				adpter.clearData();
				uploadFolloweeList();
			}
		});
	}

	// 我的关注
	private void uploadFolloweeList() {
		ALUserEngine.defauleEngine().getFolloweeList(AVUser.getCurrentUser(),
				limit, 0, new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {

						MLog.i(TAG, "getFolloweeList avexception:"
								+ avexception + "  object:" + object);

						mlistview.onRefreshComplete();
						if (avexception == null) {
							HashMap<String, List> map = (HashMap<String, List>) object;
							if (map != null) {
								List<AVUser> data = map.get("followees");
								adpter.addData(data);
							}
							adpter.notifyDataSetChanged();
						} else {
							avexception.printStackTrace();
							showSysToast("加载失败");
						}

					}
				});
	}

	// 邀请好友
	public void onInvite(View v) {
           for (int i = 0; i < layout_select.getChildCount(); i++) {
			View view = layout_select.getChildAt(i);
			AVUser user = adpter.getItemUser((String) view.getTag());
			if(user != null){
				AVObject group = CustomApplication.getInstance().currgroup;
				String message = "一起来\""+group.getString("name")+"\"聊天吧!";
				ALCCPEngine.defauleEngine().postMessageForInvite(user, group, message, new CallBack() {
					
					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "onInvite===object:"+object+" avexception:"+avexception);
						if(avexception != null)
							avexception.printStackTrace();
					}
				});
				//发送广播通知保存消息到本地
				IMChatMessage chatmessage = new IMChatMessage();
				chatmessage.setMessageDirection(IMChatMessage.MessageDirect.SENT);
				chatmessage.setMessageType(IMChatMessage.MessageType.GROUPINVITE);
				chatmessage.setMessagetime(new Date());
				chatmessage.setMessageId(String.valueOf(System.currentTimeMillis()));
				chatmessage.setMessageContent(message);
				chatmessage.setIsRead(IMChatMessage.STATE_READED);
				chatmessage.setMediaUrl(CustomApplication.getInstance().currgroup.getObjectId()); // 把群对象id保存
				chatmessage.setFromuser(new DBContactUser(user,"[群邀请]", chatmessage.getMessagetime()));
				Intent intent = new Intent(CCPIntentUtils.INTENT_IM_SAVE_DB);
				intent.putExtra("IMChatMessage", chatmessage);
				sendBroadcast(intent);
			}
			 
		}
           showSysToast("已发送");
           this.finish();
	}

	class MyAdpter extends BaseAdapter {
		private List<AVUser> userlist = new ArrayList<AVUser>();
		private Context context;

		@Override
		public int getCount() {
			return userlist.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		public MyAdpter(Context context) {
			this.context = context;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		public void addData(List<AVUser> list) {
			if (list == null)
				return;
			this.userlist.addAll(list);
		}

		public AVUser getItemUser(String userid) {
			for (int i = 0; i < userlist.size(); i++) {
				AVUser user = userlist.get(i);
				if (user.getObjectId().equals(userid)) {
					return user;
				}
			}
			return null;
		}

		public void clearData() {
			this.userlist.clear();
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			View view = LayoutInflater.from(InviteFriendsActivity.this)
					.inflate(R.layout.adpter_invitefriends, null);
			CheckBox mcheckbox = (CheckBox) view.findViewById(R.id.mcheckbox);
			final ImageView imv_heard = (ImageView) view
					.findViewById(R.id.imv_heard);
			TextView txv_name = (TextView) view.findViewById(R.id.txv_name);

			final AVUser user = userlist.get(position);
			txv_name.setText(user.getString("nickname"));
			// default image
			final int width = DensityUtil.dip2px(context, 45);
			Bitmap crclebitmap = BitmapUtils.drawCycleImage("#c4c4c5", width);
			Bitmap crclestrokebitmap = BitmapUtils.getCircleStrokbitmap(
					context, crclebitmap, width, 1, "#eeeeee");
			imv_heard.setBackgroundDrawable(new BitmapDrawable(
					crclestrokebitmap));

			aq.id(imv_heard).image(user.getString("headViewURL"), true, true,
					width, 0, new BitmapAjaxCallback() {
						@Override
						protected void callback(String url, ImageView iv,
								Bitmap bm, AjaxStatus status) {
							super.callback(url, iv, bm, status);
							Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(
									context, bm, width, 1, "#eeeeee");
							imv_heard.setImageBitmap(mbitmap);
							imv_heard.setBackgroundColor(Color.TRANSPARENT);
						}
					});

			mcheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					if (isChecked) {
						addImage(user);
					} else {
						deleteImage(user);
					}
				}
			});

			return view;
		}

	}

}
